package com.antaohua.tools.system.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.antaohua.tools.framework.base.exception.QureyEntityException;
import com.antaohua.tools.framework.base.service.BaseService;
import com.antaohua.tools.system.domain.TreeDomain;
import com.antaohua.tools.system.entity.SysDictGroupEntity;
import com.antaohua.tools.system.service.SysDictgroupService;
import com.google.common.collect.Lists;


@Transactional
@Service
public class SysDictGroupServiceImpl  extends BaseService<SysDictGroupEntity> implements SysDictgroupService{

	@Override
	public List<TreeDomain> findAllbyTree() throws QureyEntityException {
		List<SysDictGroupEntity> dictGroups = dao.findAll();
		List<TreeDomain> tree = Lists.newLinkedList();
		TreeDomain treeDomain = new TreeDomain();
		treeDomain.setLabel("数据字典");
		treeDomain = listToTree(dictGroups,treeDomain);
		tree.add(treeDomain);
		return tree;
	}

	
	private TreeDomain listToTree(List<SysDictGroupEntity> dictGroups,TreeDomain treeRoot){
		SysDictGroupEntity group = treeRoot.getData()==null?null:(SysDictGroupEntity)treeRoot.getData();
		for (SysDictGroupEntity dictGroup : dictGroups) {
			if(group==null){
				if(treeRoot.getChildren()==null){
					treeRoot.setChildren(Lists.newArrayList());
				}
				if(dictGroup.getPid()==null||dictGroup.getPid().length()!=32){
					TreeDomain itme = new TreeDomain();
					itme.setLabel(dictGroup.getName());
					itme.setData(dictGroup);
					itme = listToTree(dictGroups,itme);
					treeRoot.getChildren().add(itme);
				}
			}else if(group.getId().equals(dictGroup.getPid())){
				if(treeRoot.getChildren()==null){
					treeRoot.setChildren(Lists.newArrayList());
				}
				TreeDomain itme = new TreeDomain();
				itme.setLabel(dictGroup.getName());
				itme.setData(dictGroup);
				itme = listToTree(dictGroups,itme);
				treeRoot.getChildren().add(itme);
			}
		}
		return treeRoot;
	}
	
}
